var tag = {
    nowSelectTagArr:{
        "0":[],
        "1":[]
    },
    modelSelectTagArr:{
        "0":[],
        "1":[]
    },
    init: function (proElem,typeC,relationVal,boxElem,isShowRelation) {
        // proElem 省份元素
        // typeC 是话务小结 还是系统标签
        // relationVal 默认关系relationVal
        // boxElem 话务小结 系统标签的父元素
        // isShowRelation 是否显示关系
        if($("#tagModal").length == 0){
            tag.appendModal($('body'),isShowRelation,relationVal);
        }
        var proE = proElem;
        var proVal = "";
        if(!boxElem){
            boxElem = $('body');
        }
        // 点击标签名称输入框弹出选择标签模态框
        boxElem.find(".tagName").unbind('click').on("click", function () {
            // 区分添加还是编辑
            var codeId=$(this).parents(".modal").attr("id");
            var relation = $(this).attr("data-relation");
            var code="";

            var type=$(this).attr("data-type");
            if(codeId == "addModal"){
                code="Add";
                proE = $("#proModal"+code);

            }else if(codeId == "editModal"){
                code="Edit";
                proE = $("#proModal"+code);
            }else{
                if(!$(this).attr('data-typeC')){
                    code=typeC;
                }else{
                    code=$(this).attr('data-typeC');
                }
            }
            proVal=proE.val();
            if(proElem && proElem.hasClass('city')){
                proVal = proElem.attr("code").split("/")[0];
            }
            proVal = proVal=='CHINA'? '':proVal;
            if(!typeC){
                if(proVal == "" || proVal == "-1"){
                    toastrCog.error("请先选择省份！");
                    return
                }
            }
            tag.modelSelectTagArr[type]=[];
            if($(this).val()!=""){
                var contentsArr=$(this).val().split(",");
                var idsArr = [];
                if($(this).attr('data-tag-id')){
                    idsArr=$(this).attr('data-tag-id').split(",");//存放的id
                }else{
                    idsArr=$(this).attr('data-id').split(",");//存放的路径
                }
                for(var i=0;i<contentsArr.length;i++){
                    var obj={};
                    obj.content=contentsArr[i];
                    obj.id=idsArr[i];
                    if(obj.id !== '全部'){
                        tag.modelSelectTagArr[type].push(obj);
                    }
                }
            }
            var proId = bs.getXInY(tools.proArr,"id","value",proVal);
            if(proId == -1){ // 如果省份id 不存在 则显示全国标签树
                proId = ''
            }
            $("#areaTreeId").val(proId);
            menuTag.render($("#jstreeTag"),code,type,proVal);
            if($('input[name="relation"][value = "'+relationVal+'"]').length>0){
                if(relation === undefined || relation === ''){
                    relation = relationVal
                }
                $('input[name="relation"][value = "'+relation+'"]').prop('checked',true);
            }

            $("#tagModal").modal("show").attr({"data-code":code,"data-type":type,'data-pro-id':proId});
            $("#tagProperty").val(type);
            var tagTable = new TableInitTag();
            tagTable.Init('0');//加载标签表格

            if(type==0){
                $("#tagModal").find("h4").html("选择话务小结");
            }else{
                $("#tagModal").find("h4").html("选择系统标签");
            }
            if(tag.modelSelectTagArr){
                tag.nowSelectTagArr[type]=bs.objArrDeepCopy(tag.modelSelectTagArr[type]);
            }
        });
        // 点击查询按钮 搜索具体标签
        $("#searchTagName").on("click", function () {
            var tagTable = new TableInitTag();
            tagTable.Init('0');
        });
        // 点击全查询按钮 搜索具体标签
        $("#searchAllTagName").on("click", function () {
            $("#tagTreeId").val("");
            $("#areaTreeId").val($("#tagModal").attr('data-pro-id'));
            $("#tagProperty").val($("#tagModal").attr('data-type'));
            $("#jstreeTag").jstree("deselect_all", true);
            var tagTable = new TableInitTag();
            tagTable.Init('1');
        });
        // 保存已选标签
        $("#save").on("click", function () {
            var type= $("#tagModal").attr("data-type");
            var selectArr = tag.modelSelectTagArr[type];
            var length = selectArr.length;
            var arr = [];
            var nameArr = [];
            var code= $("#tagModal").attr("data-code");
            for (var i = 0; i < length; i++) {
                var id = selectArr[i].id;
                var name = selectArr[i].content;
                arr.push(id);
                nameArr.push(name);
            }
            $("#tagTraffic"+code+type).val(nameArr.join(","))
                .attr("title", nameArr.join(","))
                .attr("data-id", nameArr.join(","))
                .attr("data-tag-id", arr.join(","))
                .attr("data-relation", $('input[name="relation"]:checked').val());
            $("#tagModal").modal("hide");
        });
        // 关闭标签弹框 不保存本次已选记录 恢复为上一次保存记录
        $(".closeAudioModel").unbind('click').on("click",function(){
            var type= $("#tagModal").attr("data-type");
            tag.modelSelectTagArr[type]=bs.objArrDeepCopy(tag.nowSelectTagArr[type]);
        });
        // 弹框隐藏事件
        $("#tagModal").on("hide.bs.modal", function () {
            $("#searchMenuTag").prev().val("");//清空搜索内容
            $("#tagTreeName").val("");
            $("#tagTreeId").val("");
        });
        // 删除已选标签
        $("#tagModal .tagSModel").on("click", "li b", function () {
            var type= $("#tagModal").attr("data-type");
            var $li=$(this).parents("li");
            var content = $li.text();
            for(var i=0;i<tag.modelSelectTagArr[type].length;i++){
                var contentOld=tag.modelSelectTagArr[type][i].content;
                if(contentOld == content){
                    tag.modelSelectTagArr[type].splice(i,1)
                }
            }
            $li.remove();
            $("#tagTableWin").bootstrapTable('refresh');
        });
        //全部删除
        $("#tagModal").on("click", "#deleteAllTag", function () {
            var type= $("#tagModal").attr("data-type");
            tag.modelSelectTagArr[type] = [];
            $('#tagTableWin').bootstrapTable("refresh");
        });
    },
    appendModal:function(elem,isShowRelation,relationVal){
        var classStr = '';
        var orVAl = '0';
        var andVAl = '1';
        if(isShowRelation){
            classStr = 'hidden'
        }else{
            if(relationVal == 'should' || relationVal == 'must'){
                orVAl = 'should'
                andVAl = 'must'
            }
        }

        var str = '<div class="modal fade" id="tagModal" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static">' +
            '<div class="modal-dialog" style="width: 1000px;">' +
                '<div class="modal-content">' +
                    '<div>' +
                        '<div class="modal-header">' +
                            '<button type="button" class="close closeAudioModel" data-dismiss="modal">' +
                                '<span aria-hidden="true">&times;</span>' +
                                '<span class="sr-only">Close</span>' +
                            '</button>' +
                        '<h4 class="modal-title">选择标签</h4>' +
                    '</div>' +
                '<div class="modal-body">' +
                '<div class="selectModel" style="height:570px !important;">' +
                    '<div class="menu_left">' +
                        '<div class="search_box">' +
                        '<input type="text" autocomplete="off" style="width: 169px;">' +
                        '<span class="fa fa-search fa_btn" id="searchMenuTag"></span>' +
                        '</div>' +
                        '<div id="jstreeTag" class="scrollbar">' +
                        '</div>' +
                    '</div>' +
                '<div class="model_right" style="width:480px;height: 100%;">' +
                    '<div class="search_box">' +
                    '<input type="text" autocomplete="off" placeholder="标签名称" style="width: 381px;" id="tagTreeName">' +
                    '<span class="fa_btn_search" id="searchTagName">查询</span>\n' +
                    '<span class="fa_btn_search" id="searchAllTagName">全查询</span>\n' +
                    '</div>' +
                    '<table id="tagTableWin"></table>' +
                '</div>' +
                '<div class="model_right" style="width: 270px;height: 546px;">' +
                    '<div class="tagSModel">' +
                        '<div class="radio">已选标签：' +
                        '<label style="margin-right:20px;" class="'+classStr+'"><input type="radio" name="relation" value="'+orVAl+'">取并集</label>' +
                        '<label class="'+classStr+'"><input type="radio" name="relation" value="'+andVAl+'">取交集</label>' +
                        '<span class="fa_btn_search deleteAllTag" id="deleteAllTag">全删</span>' +
                        '</div>' +
                        '<ul style="overflow: auto;height: 556px;"></ul>' +
                    '</div>' +
                '</div>' +
            '</div>' +
            '</div>' +
            '<div class="modal-footer">' +
            '<button type="button" class="btn btn-primary" id="save">保存</button>' +
            '<button type="button" class="btn btn-white closeAudioModel" data-dismiss="modal" id="close">关闭</button>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';
        elem.append(str);
    },
    renderSelectTag: function () {
        var type= $("#tagModal").attr("data-type");
        var ul = $(".tagSModel ul");
        ul.html("");
        if(tag.modelSelectTagArr && tag.modelSelectTagArr[type]){
            if(tag.modelSelectTagArr[type].length>0){
                for (var i = 0; i < tag.modelSelectTagArr[type].length; i++) {
                    var content = tag.modelSelectTagArr[type][i].content;
                    if (content == null) {
                        content = ""
                    }
                    var $li=$('<li title="分类：'+content+'">'+content+'<b class="fa fa-close noPer" style="display: none" title="删除标签"></b></li>');
                    $li.hover(function () {
                        $(this).find("b").show();
                    }, function () {
                        $(this).find("b").hide();
                    });
                    ul.append($li);
                }
            }
        }
    },
    clearTag: function () {
        $("#jstreeTag").jstree("deselect_all", true);
        $("#selTagName").html("");
        $(".tagName").val("").attr({"data-id": "","title":"",'data-relation':'','data-tag-id':''});
        $("#searchMenuTag").prev().val("");
        tag.modelSelectTagArr={
            "0":[],
            "1":[]
        };
        var tagTable = new TableInitTag();
        tagTable.Init('0');
    }
};
var menuTag = {
    render: function (elem,code,type,proVal) {
        var jstree = elem;
        elem.jstree("destroy");
        elem.data('jstree', false).empty();
        var id =bs.getXInY(tools.proArr,"id","value",proVal);
        id = id == '-1' ? '' : id;
        jstree.jstree({
            "core": {
                "animation": false,
                "multiple": false,
                "check_callback": true,
                'data': function (obj, callback) {
                    $.ajax({
                        type: "GET",
                        url: basePath + 'rest/busTag/showTagTree',
                        data:{
                            "areaId":id,
                            "tagType":type
                        },
                        success: function (result) {
                            callback.call(this, menuTag.loopMenu(result.children));
                            menuTag.changeMenu(elem);
                            menuTag.search(elem);
                        }
                    });
                }
            },
            "types": {
                "default": {
                    "icon": "jstree-folder"
                },
                "html": {
                    "icon": "jstree-file"
                }
            },
            "plugins": ["types", "search", "unique", "contextmenu", "changed"]
        }).bind('loaded.jstree', function (e, data) {
            jstree.jstree("deselect_all", true);
            $("li[aria-selected='true']").click();
        });
    },
    getNoteInID: function (id) {
        var str = "";
        $.ajax({
            type: "post",
            url: basePath + 'rest/busTag/getTagByPK',
            async: false,
            data: {
                id: id
            },
            success: function (result) {
                if (result != null) {
                    str = result.note
                }
            }
        });
        return str;
    },
    loopMenu: function (array) {
        if (array.length > 0) {
            for (var i = 0; i < array.length; i++) {
                var children = array[i]["children"];
                if (children.length <= 0) {
                    array[i].type = "html"
                } else {
//                        array[i].state = {"opened": "false"}
                }
                array[i].state = {"opened": false}
                if (children) {
                    menuTag.loopMenu(children);
                }
            }
            return array;
        }else{
            return [];
        }
    },
    changeMenu: function (elem) {
        elem.unbind("changed.jstree").on("changed.jstree", function (e, data) {
            // 当选中某个节点时 表格重新加载
            var selectNode = $("#jstreeTag").jstree("get_node", data.selected);
            if (data.selected.length > 0) {
                if (data.selected > 0) {  //如果选中的节点不是省份信息
                    // 选中的是标签节点 把选中的节点值放到tagId中
                    $("#areaTreeId").val(selectNode.original.areaId);
                    $("#tagTreeId").val(selectNode.original.tagId);
                    $("#tagTreeType").val(selectNode.original.tagType);
                } else{
                    // 判断节点level 从而判断是选中的省份节点还是标签标识节点
                    var level = selectNode.original.level;
                    if(level == 2){
                        // 选中的是标识节点 获取省份id 清空tagId
                        $("#areaTreeId").val(selectNode.original.areaId);
                        $("#tagTreeId").val("");
                        $("#tagTreeType").val(selectNode.original.tagType);
                    }else {
                        // 选中的是省份节点 获取省份id 清空标识id和tagId
                        $("#areaTreeId").val(selectNode.original.areaId);
                        $("#tagTreeId").val("");
                        $("#tagTreeType").val("");
                    }
                }
                var tagTable = new TableInitTag();
                tagTable.Init('0');
            }

        });
    },
    search: function (elem) {
        $("#searchMenuTag").unbind("click").on("click", function () {
            elem.jstree(true).search($.trim($(this).prev().val()));
            menuTag.scrollSearch(elem);
        });
        $("#searchMenuTag").prev().unbind("keyup").on("keyup", function (e) {
            var code = e.charCode || e.keyCode;
            if (code == 13) {
                elem.jstree(true).search($.trim($(this).val()));
                menuTag.scrollSearch(elem);
            }
        })
    },
    scrollSearch: function (elem) {
        if (elem.find(".jstree-search").length > 0) {
            var odiv = elem.find(".jstree-search").eq(0)[0];
            var top = odiv.offsetTop;
            var height = odiv.offsetHeight;
            var elemTop = elem[0].scrollTop;
            //获取当前屏幕大小
            var size = elem.height();
            //加上元素本身的高度，是元素全部出现事件
            if ((top + height) < (elemTop + size) && (top + height) > elemTop) {
            } else {
                elem.animate({scrollTop: top - 70}, "slow");
            }
        }
    },
    getMenuData: function () {
        var arr = [];
        $.ajax({
            type: "GET",
            url: basePath + 'rest/busTag/showTagTree',
            async: false,
            success: function (result) {
                if (result != null) {
                    arr.push(result);
                }
            }
        });
        return arr;
    },
    refresh: function (elem) {
        var tree = elem;
        tree.jstree(true).settings.core.data = menuTag.loopMenu(menuTag.getMenuData(), false); // 新数据
        tree.jstree(true).refresh(); //刷新树
    }
};
var TableInitTag = function () {
    var oTableInit = new Object();
    //初始化Table
    oTableInit.Init = function (code) {
        var url = ''
        if(code == 1){// 如果是 全查询
            url = basePath + "/rest/busTag/busTagAllByPage";
        }else{// 如果是 查询
            url = basePath + "/rest/busTag/busTagByPage";
        }
        $('#tagTableWin').bootstrapTable("destroy");
        $('#tagTableWin').bootstrapTable({
            url: url,         //请求后台的URL（*）
            method: "post", //请求方式（*）
            dataType: "json",
            contentType: "application/x-www-form-urlencoded;charset=UTF-8",
            dataField: "rows", //服务端返回数据键值 就是说记录放的键值是rows，分页时使用总记录数的键值为total
            totalField: "total",
            striped: true, //是否显示行间隔色
            cache: false, //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: true, //是否显示分页（*）
            sortable: false, //是否启用排序
            sortName: "id", //排序方式
            sortOrder: "asc", //排序方式
            clickToSelect: true,
            queryParams: oTableInit.queryParams, //传递参数（*）
            queryParamsType: "", //  queryParamsType = 'limit' 参数: limit, offset, search, sort, order;
            sidePagination: "server", //分页方式：client客户端分页，server服务端分页（*）
            pageNumber: 1, //初始化加载第一页，默认第一页
            pageSize: 10, //每页的记录行数（*）
            pageList: [10, 15, 20, 25], //可供选择的每页的行数（*）
            idField: "id",
            uniqueId: "id", //每一行的唯一标识，一般为主键列
            responseHandler: function (res) {
                var type= $("#tagModal").attr("data-type");
                $(".tags li").each(function () {
                    var id = $(this).attr("data-tag-id");
                    var name = $(this).find("span").html();
                    var tagtype = $(this).attr("data-type");
                    var obj = {};
                    obj.id = id;
                    obj.name = name;
                    obj.tagtype = tagtype;
                    if (tag.modelSelectTagArr) {
                        var str = "";
                        for (var i = 0; i < tag.modelSelectTagArr[type].length; i++) {
                            if (tag.modelSelectTagArr[type][i].content == content) {
                                str += "0";
                            }
                        }
                        if (str.indexOf("0") < 0) {
                            tag.modelSelectTagArr[type].push(obj);
                        }
                    } else {
                        tag.modelSelectTagArr[type].push(obj);
                    }
                });
                var selectArr = tag.modelSelectTagArr[type];
                var arr = res.result;
                if (selectArr && selectArr.length > 0 && arr && arr.length > 0) {
                    for (var i = 0; i < arr.length; i++) {
                        for (var j = 0; j < selectArr.length; j++) {
                            if (selectArr[j]["content"] == arr[i]["content"]) {
                                arr[i]["state"] = true;
                            }
                        }
                    }
                }
                return {
                    "total": res.totalCount,//总页数
                    "rows": arr   //数据
                };
            },
            columns: [
                {
                    checkbox: true, // 显示一个勾选框
                    align: 'center', // 居中显示
                    formatter: function (value, row, index) {
                        if (row.state == true)
                            return {
                                disabled: false,//设置是否可用
                                checked: true//设置选中
                            };
                        return value;
                    }
                },
                {
                    align: "center",
                    halign: "center",
                    title: '序号',//标题  可不加
                    width: 60,
                    field: 'id',
                    sortable: true,
                    formatter: function (value, row, index) {
                        var getOptions = $("#tagTableWin").bootstrapTable('getOptions');
                        var pagenum = getOptions.pageNumber;
                        var pagesize = getOptions.pageSize;
                        var st = (pagenum - 1) * pagesize;
                        return (st + index + 1) + "";
                    }
                },
                {
                    align: "center",
                    halign: "center",
                    field: 'provincename',
                    title: '省份',
                    sortable: true
                },
                {
                    align: "center",
                    halign: "center",
                    field: 'content',
                    title: '标签分类',
                    sortable: true
                }, {
                    align: "center",
                    halign: "center",
                    field: 'name',
                    title: '标签名称',
                    sortable: true
                }
            ],
            onLoadSuccess: function (data) {  //加载成功时执行
                tag.renderSelectTag();
                if (!data.total || data.total == 0) {
                    $(".no-records-found").find("td").html('无匹配数据');
                }
            },
            onLoadError: function () {  //加载失败时执行
                $(".no-records-found").find("td").html('无匹配数据');
            },
            onCheck: function (row, tr) {
                var type= $("#tagModal").attr("data-type");
                tag.modelSelectTagArr[type].push(row);
                tag.renderSelectTag();
            },
            onUncheck: function (row, tr) {
                var type= $("#tagModal").attr("data-type");
                var content = row.content;
                for (var i = 0; i < tag.modelSelectTagArr[type].length; i++) {
                    if (tag.modelSelectTagArr[type][i].content == content) {
                        tag.modelSelectTagArr[type].splice(i, 1)
                    }
                }
                tag.renderSelectTag();
            },
            onCheckAll: function (row, tr) {
                var type= $("#tagModal").attr("data-type");
                var selectArr = $("#tagTableWin").bootstrapTable("getSelections");
                var oldArr = bs.objArrDeepCopy(tag.modelSelectTagArr[type]);
                for (var j = 0; j < selectArr.length; j++){
                    var strCode = '';
                    if(oldArr.length>0){
                        for (var i = 0; i < oldArr.length; i++) {
                            if (oldArr[i].content == selectArr[j].content) {
                                strCode += '1'
                            }
                        }
                    }
                    if(strCode.indexOf('1')==-1){
                        tag.modelSelectTagArr[type].push(selectArr[j])
                    }
                }
                tag.renderSelectTag();
            },
            onUncheckAll: function (rowsAfter, rowsBefore) {
                var type= $("#tagModal").attr("data-type");
                var selectArr = rowsAfter;
                for (var j = 0; j < selectArr.length; j++){
                    for (var i = 0; i < tag.modelSelectTagArr[type].length; i++) {
                        if (tag.modelSelectTagArr[type][i].content == selectArr[j].content) {
                            tag.modelSelectTagArr[type].splice(i, 1)
                            break
                        }
                    }
                }
                tag.renderSelectTag();
            },
            onResetView: function (data) {
                $("#tagModal .fixed-table-body").css("maxHeight", 430 + "px");
            },
            formatLoadingMessage: function () {
                return '<div class="loaded">' +
                    '<div class="loader">' +
                    '<div class="loader-inner line-scale-pulse-out">' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '<div></div>' +
                    '</div>' +
                    '</div>' +
                    '</div>' +
                    '<div>请稍等，数据正在加载中...</div>';
            }
        });
    };
    //得到查询的参数
    oTableInit.queryParams = function (params) {
        var temp = { //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
            "pageSize": params.pageSize,
            "pageNum": params.pageNumber,
            "sortName": this.sortName,
            "sortOrder": this.sortOrder,
            "areaId": $.trim($("#areaTreeId").val()),
            "tagType": $.trim($("#tagProperty").val()),
            "tagId": $.trim($("#tagTreeId").val()),
            "tagName": $.trim($("#tagTreeName").val())
        };
        return temp;
    };
    return oTableInit;
};